package com.example.utils;



import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ProjectName: posreview
 * @Package: com.zhitu.posreview.utils
 * @ClassName: PathUtils
 * @Author: zhengchaorui
 * @Description: 相对路径解析工具类
 * @Date: 2019/5/13 15:46
 * @Version: 1.0.0
 */
@Slf4j
@Service
public class PathUtils {
    /**
     * 生成pdf文件
     *
     * @param map          模板中数据的键值对   map 中存入两个键值对  文字填充（"data",Map）图片填充("image",Map)
     * @param templatePath 模板路径
     * @return
     */
    public  ByteArrayOutputStream generatePdf(Map<String, Map> map, String templatePath) {
        //生产pdfreader
        PdfReader reader = null;
        try {
            reader = new PdfReader(templatePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            /* 读取*/
            PdfStamper pdfStamper = new PdfStamper(reader, bos);
            /*设置字体格式*/

            ArrayList<BaseFont> fontList = new ArrayList<>();
            AcroFields s = pdfStamper.getAcroFields();
            s.setSubstitutionFonts(fontList);
            /*Field , 这个是自己在pdf上定义的变量名称*/

            // 处理数据
            Map data = map.get("data");
            for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {
                if (!CollectionUtils.isEmpty(data) && data.get(entry.getKey()) != null) {
                    s.setField(entry.getKey(), data.get(entry.getKey()).toString(), true);
                }
            }
            // 处理图片
            Map imageMap = map.get("image");
            for (Map.Entry<String, AcroFields.Item> entry : s.getFields().entrySet()) {
                if (!CollectionUtils.isEmpty(imageMap) && imageMap.get(entry.getKey()) != null) {
                    String key = entry.getKey();
                    String value = imageMap.get(entry.getKey()).toString();
                    int pageNo = s.getFieldPositions(key).get(0).page;
                    Rectangle signRect = s.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    //根据路径读取图片
                    Image image = Image.getInstance(value);
                    //获取图片页面
                    PdfContentByte under = pdfStamper.getOverContent(pageNo);
                    //图片大小自适应
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    //添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }
            }
            pdfStamper.setFormFlattening(true);
            pdfStamper.close();
            return bos;
        } catch (Exception e) {
            log.info("pdf文件生成失败");
            e.printStackTrace();
        }

        return null;
    }


    /**
     * 输出本地
     *
     * @param bos pdf字节流
     * @throws DocumentException
     * @throws IOException
     */
    public void extracted(ByteArrayOutputStream bos) {
        Document doc = new Document();
        // 输出流
        FileOutputStream out = null;
        try {
            // 本地输出路径（可根据自己需要自定义）
            out = new FileOutputStream("F:\\" + System.currentTimeMillis() + ".pdf");
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }

    }


}


